package com.bingxu.flink.chapter01;

/**
 * @author :BingXu
 * @description :TODO
 * @date :2021/8/6 18:42
 * @modifier :
 */

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * 通过监听socket port 演示无界流
 */
public class FlinkUnBoundStreamWCDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment eseEnv = StreamExecutionEnvironment.getExecutionEnvironment();

        // 监听nc的socket信息
        DataStreamSource<String> portDS = eseEnv.socketTextStream("hadoop102", 9890);

        SingleOutputStreamOperator<Tuple2<String, Integer>> sumDS = portDS.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                String[] words = s.split(" ");
                for (String word : words) {
                    collector.collect(Tuple2.of(word, 1));
                }
            }
        }).keyBy(0).sum(1);

        sumDS.print();

        // 启动环境对象
        eseEnv.execute();
    }
}
